package com.chen.authority.common.util;

import cn.hutool.core.util.NumberUtil;
import com.chen.authority.model.bo.ServerBo;
import com.chen.authority.model.vo.*;
import oshi.hardware.CentralProcessor;
import oshi.hardware.GlobalMemory;
import oshi.hardware.HardwareAbstractionLayer;
import oshi.software.os.FileSystem;
import oshi.software.os.OSFileStore;
import oshi.software.os.OperatingSystem;
import oshi.util.Util;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;

/**
 * 系统工具类
 *
 * @author chengy
 * @date 2022/09/29
 */
public class SystemUtil {

    /**
     * 系统信息
     */
    private static final oshi.SystemInfo systemInfo;

    /**
     * 硬件信息
     */
    private static final HardwareAbstractionLayer hardware;

    static {
        systemInfo = new oshi.SystemInfo();
        hardware = systemInfo.getHardware();
    }

    /* 系统等待时间 */
    private static final int SYSTEM_WAIT_SECOND = 1000;

    /**
     * 获取cpu信息
     *
     * @param processor {@link CentralProcessor}
     * @return cpu信息
     */
    public static CpuVo getCpuInfo(CentralProcessor processor) {
        CpuVo cpu = new CpuVo();

        long[] prevTicks = processor.getSystemCpuLoadTicks();
        Util.sleep(SYSTEM_WAIT_SECOND);

        long[] ticks = processor.getSystemCpuLoadTicks();
        long nice = ticks[CentralProcessor.TickType.NICE.getIndex()] - prevTicks[CentralProcessor.TickType.NICE.getIndex()];
        long irq = ticks[CentralProcessor.TickType.IRQ.getIndex()] - prevTicks[CentralProcessor.TickType.IRQ.getIndex()];
        long softirq = ticks[CentralProcessor.TickType.SOFTIRQ.getIndex()] - prevTicks[CentralProcessor.TickType.SOFTIRQ.getIndex()];
        long steal = ticks[CentralProcessor.TickType.STEAL.getIndex()] - prevTicks[CentralProcessor.TickType.STEAL.getIndex()];
        long cSys = ticks[CentralProcessor.TickType.SYSTEM.getIndex()] - prevTicks[CentralProcessor.TickType.SYSTEM.getIndex()];
        long user = ticks[CentralProcessor.TickType.USER.getIndex()] - prevTicks[CentralProcessor.TickType.USER.getIndex()];
        long ioWait = ticks[CentralProcessor.TickType.IOWAIT.getIndex()] - prevTicks[CentralProcessor.TickType.IOWAIT.getIndex()];
        long idle = ticks[CentralProcessor.TickType.IDLE.getIndex()] - prevTicks[CentralProcessor.TickType.IDLE.getIndex()];
        long totalCpu = user + nice + cSys + idle + ioWait + irq + softirq + steal;

        cpu.setCpuNum(processor.getLogicalProcessorCount());
        cpu.setTotal(totalCpu);
        cpu.setSys(cSys);
        cpu.setUsed(user);
        cpu.setWait(ioWait);
        cpu.setFree(idle);

        return cpu;
    }

    /**
     * 获取内存信息
     *
     * @param globalMemory {@link GlobalMemory}
     * @return 内存信息
     */
    public static MemoryVo getMemoryInfo(GlobalMemory globalMemory) {
        MemoryVo memory = new MemoryVo();
        memory.setTotal(globalMemory.getTotal());
        memory.setUsed(globalMemory.getTotal() - globalMemory.getAvailable());
        memory.setFree(globalMemory.getAvailable());
        return memory;
    }

    /**
     * 获取Java虚拟机信息
     *
     * @return Java虚拟机信息
     */
    public static JvmVo getJvmInfo() {
        JvmVo jvm = new JvmVo();
        Properties props = System.getProperties();
        jvm.setTotal(Runtime.getRuntime().totalMemory());
        jvm.setMax(Runtime.getRuntime().maxMemory());
        jvm.setFree(Runtime.getRuntime().freeMemory());
        jvm.setVersion(props.getProperty("java.version"));
        jvm.setHome(props.getProperty("java.home"));
        return jvm;
    }

    /**
     * 获取系统信息
     *
     * @return 系统信息
     * @throws UnknownHostException 未知主机异常
     */
    public static SystemVo getSysInfo() throws UnknownHostException {
        SystemVo sys = new SystemVo();
        Properties props = System.getProperties();
        sys.setComputerName(InetAddress.getLocalHost().getHostName());
        sys.setComputerIp(InetAddress.getLocalHost().getHostAddress());
        sys.setOsName(props.getProperty("os.name"));
        sys.setOsArch(props.getProperty("os.arch"));
        sys.setUserDir(props.getProperty("user.dir"));
        return sys;
    }

    /**
     * 获取磁盘信息
     *
     * @param os {@link OperatingSystem}
     * @return 磁盘信息
     */
    public static List<SystemFileVo> getSysFiles(OperatingSystem os) {
        List<SystemFileVo> sysFiles = new LinkedList<>();

        FileSystem fileSystem = os.getFileSystem();
        List<OSFileStore> fsArray = fileSystem.getFileStores();

        for (OSFileStore fs : fsArray) {
            long free = fs.getUsableSpace();
            long total = fs.getTotalSpace();
            long used = total - free;
            SystemFileVo sysFile = new SystemFileVo();
            sysFile.setDirName(fs.getMount());
            sysFile.setSysTypeName(fs.getType());
            sysFile.setTypeName(fs.getName());
            sysFile.setTotal(FileUtil.convertFileSize(total));
            sysFile.setFree(FileUtil.convertFileSize(free));
            sysFile.setUsed(FileUtil.convertFileSize(used));
            sysFile.setUsage(NumberUtil.mul(NumberUtil.div(used, total, 4), 100));
            sysFiles.add(sysFile);
        }

        return sysFiles;
    }

    /**
     * 获取服务器信息
     *
     * @return 服务器信息
     */
    public static ServerBo getServerInfo() throws Exception {
        ServerBo server = new ServerBo();

        server.setJvm(getJvmInfo());
        server.setSystem(getSysInfo());
        server.setCpu(getCpuInfo(hardware.getProcessor()));
        server.setMemory(getMemoryInfo(hardware.getMemory()));
        server.setSystemFile(getSysFiles(systemInfo.getOperatingSystem()));

        return server;
    }

}